package dxn.nl.file.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import dxn.boot.common.entity.CsColumnDto;
import dxn.nl.file.biz.dao.AppModelDao;
import dxn.nl.file.biz.dao.UserImportColumnDao;
import dxn.nl.file.biz.dto.CsBaseDataDto;
import dxn.nl.file.biz.po.AppModelPo;
import dxn.nl.file.biz.po.UserImportColumnPo;
import dxn.nl.file.biz.service.AppModelBaseService;
import dxn.nl.file.client.model.enums.ExportFileTypeEnum;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;

@Service
public class AppModelBaseServiceImpl extends ServiceImpl<AppModelDao, AppModelPo> implements AppModelBaseService {

    @Resource
    private UserImportColumnDao userImportColumnDao;

    @Override
    public List<CsColumnDto> selectColumnsTemplateBy(String modeCode, int type) {
        LambdaQueryWrapper<AppModelPo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(AppModelPo::getModeCode, modeCode)
                .in(AppModelPo::getTypeCode, type);
        lambdaQueryWrapper.select(AppModelPo::getColumnList);
        AppModelPo appModelPo = this.baseMapper.selectOne(lambdaQueryWrapper);
        if(appModelPo == null)
        {
            return null;
        }
        return appModelPo.getColumnList();
    }

    @Override
    public List<CsColumnDto> selectExportTemplateByModeCode(String modeCode) {
        return selectColumnsTemplateBy(modeCode, ExportFileTypeEnum.export.code);
    }

    @Override
    public List<CsColumnDto> selectImportTemplateByUser(String orgCode, String userCode, String modeCode) {

        List<CsColumnDto> list = selectColumnsTemplateBy(modeCode, ExportFileTypeEnum.export.code);

        LambdaQueryWrapper<UserImportColumnPo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserImportColumnPo::getModeCode, modeCode)
                .in(UserImportColumnPo::getUserCode, userCode);

        UserImportColumnPo userImportColumnPo = userImportColumnDao.selectOne(lambdaQueryWrapper);
        if(userImportColumnPo == null || CollectionUtils.isEmpty(userImportColumnPo.getColumns()))
        {
            return list;
        }

        HashMap<String,String> map = new HashMap<>();
        for(CsBaseDataDto dto:userImportColumnPo.getColumns())
        {
            map.put(dto.getCode(),dto.getName());
        }

        for(CsColumnDto dto : list)
        {
            String title = map.get(dto.getDataIndex());
            if(StringUtils.isNotBlank(title))
            {
                dto.setTitle(title);
            }
        }

        return list;
    }
}
